package org.jeecg.modules.demo.rockslopestablesetting.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.rockslopestablesetting.entity.RockSlopeStableSetting;
import org.jeecg.modules.demo.rockslopestablesetting.service.IRockSlopeStableSettingService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.sloperiskevaluationsetting.entity.SlopeRiskEvaluationSetting;
import org.jeecg.modules.demo.sloperiskevaluationsetting.service.ISlopeRiskEvaluationSettingService;
import org.jeecg.modules.demo.slopestablesetting.entity.SlopeStableSetting;
import org.jeecg.modules.demo.slopestablesetting.service.ISlopeStableSettingService;
import org.jeecg.modules.demo.soilrockslopesetting.entity.SoilRockSlopeSetting;
import org.jeecg.modules.demo.soilrockslopesetting.service.ISoilRockSlopeSettingService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.cache.annotation.Cacheable;

/**
 * @Description: 岩质边坡稳定性评价因子权重及赋值表
 * @Author: jeecg-boot
 * @Date:   2025-06-21
 * @Version: V1.0
 */
@Api(tags="岩质边坡稳定性评价因子权重及赋值表")
@RestController
@RequestMapping("/rockslopestablesetting/rockSlopeStableSetting")
@Slf4j
public class RockSlopeStableSettingController extends JeecgController<RockSlopeStableSetting, IRockSlopeStableSettingService> {
	@Autowired
	private IRockSlopeStableSettingService rockSlopeStableSettingService;
	//土质
	@Autowired
	private ISlopeStableSettingService slopeStableSettingService;
	//混合
	@Autowired
	private ISoilRockSlopeSettingService soilRockSlopeSettingService;
//	斜坡单元风险评价因子
	@Autowired
	private ISlopeRiskEvaluationSettingService slopeRiskEvaluationSettingService;

	 @Autowired
	 private RedisUtil redisUtil;
	// 定义缓存 Key（可根据项目结构提取到 Constant 类中）
	private static final String CACHE_KEY_ROCK_SLOPE = "config:rock_slope_stable_setting";
	private static final String CACHE_KEY_SLOPE = "config:slope_stable_setting";
	private static final String CACHE_KEY_SOIL_ROCK_SLOPE = "config:soil_rock_slope_setting";
	private static final String CACHE_KEY_SLOPE_RISK = "config:slope_risk_evaluation_setting";
	
	/**
	 * 分页列表查询
	 *
	 * @param rockSlopeStableSetting
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "岩质边坡稳定性评价因子权重及赋值表-分页列表查询")
	@ApiOperation(value="岩质边坡稳定性评价因子权重及赋值表-分页列表查询", notes="岩质边坡稳定性评价因子权重及赋值表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<RockSlopeStableSetting>> queryPageList(RockSlopeStableSetting rockSlopeStableSetting,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        QueryWrapper<RockSlopeStableSetting> queryWrapper = QueryGenerator.initQueryWrapper(rockSlopeStableSetting, req.getParameterMap());
		Page<RockSlopeStableSetting> page = new Page<RockSlopeStableSetting>(pageNo, pageSize);
		IPage<RockSlopeStableSetting> pageList = rockSlopeStableSettingService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param rockSlopeStableSetting
	 * @return
	 */
	@AutoLog(value = "岩质边坡稳定性评价因子权重及赋值表-添加")
	@ApiOperation(value="岩质边坡稳定性评价因子权重及赋值表-添加", notes="岩质边坡稳定性评价因子权重及赋值表-添加")
	@RequiresPermissions("rockslopestablesetting:rock_slope_stable_setting:add")
	@PostMapping(value = "/add")
	@CacheEvict(cacheNames = "config:rock_slope_stable_setting", allEntries = true)
	public Result<String> add(@RequestBody RockSlopeStableSetting rockSlopeStableSetting) {
		rockSlopeStableSettingService.save(rockSlopeStableSetting);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param rockSlopeStableSetting
	 * @return
	 */
	@AutoLog(value = "岩质边坡稳定性评价因子权重及赋值表-编辑")
	@ApiOperation(value="岩质边坡稳定性评价因子权重及赋值表-编辑", notes="岩质边坡稳定性评价因子权重及赋值表-编辑")
	@RequiresPermissions("rockslopestablesetting:rock_slope_stable_setting:edit")
	@CacheEvict(cacheNames = "config:rock_slope_stable_setting", allEntries = true)
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody RockSlopeStableSetting rockSlopeStableSetting) {
		rockSlopeStableSettingService.updateById(rockSlopeStableSetting);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "岩质边坡稳定性评价因子权重及赋值表-通过id删除")
	@ApiOperation(value="岩质边坡稳定性评价因子权重及赋值表-通过id删除", notes="岩质边坡稳定性评价因子权重及赋值表-通过id删除")
	@RequiresPermissions("rockslopestablesetting:rock_slope_stable_setting:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		rockSlopeStableSettingService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "岩质边坡稳定性评价因子权重及赋值表-批量删除")
	@ApiOperation(value="岩质边坡稳定性评价因子权重及赋值表-批量删除", notes="岩质边坡稳定性评价因子权重及赋值表-批量删除")
	@RequiresPermissions("rockslopestablesetting:rock_slope_stable_setting:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.rockSlopeStableSettingService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "岩质边坡稳定性评价因子权重及赋值表-通过id查询")
	@ApiOperation(value="岩质边坡稳定性评价因子权重及赋值表-通过id查询", notes="岩质边坡稳定性评价因子权重及赋值表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<RockSlopeStableSetting> queryById(@RequestParam(name="id",required=true) String id) {
		RockSlopeStableSetting rockSlopeStableSetting = rockSlopeStableSettingService.getById(id);
		if(rockSlopeStableSetting==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(rockSlopeStableSetting);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param rockSlopeStableSetting
    */
    @RequiresPermissions("rockslopestablesetting:rock_slope_stable_setting:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, RockSlopeStableSetting rockSlopeStableSetting) {
        return super.exportXls(request, rockSlopeStableSetting, RockSlopeStableSetting.class, "岩质边坡稳定性评价因子权重及赋值表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("rockslopestablesetting:rock_slope_stable_setting:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, RockSlopeStableSetting.class);
    }

	//进行redis缓存
	 @AutoLog(value = "岩质边坡稳定性评价因子权重及赋值表-进行redis缓存")
	 @ApiOperation(value="岩质边坡稳定性评价因子权重及赋值表-进行redis缓存", notes="岩质边坡稳定性评价因子权重及赋值表-进行redis缓存")
	 @PostMapping(value = "/redisCache")
	 public Result<?> redisCache() {
		 // 先尝试从Redis获取缓存
		 String cacheKey = "config:rock_slope_stable_setting";
		 RockSlopeStableSetting rockSlopeStableSetting = (RockSlopeStableSetting) redisUtil.get(cacheKey);
		 if (oConvertUtils.isNotEmpty (rockSlopeStableSetting)) {
			 return Result.OK("从Redis缓存获取数据成功");
		 }
		//查询数据库数据进行缓存
		 LambdaQueryWrapper<RockSlopeStableSetting> queryWrapper = new LambdaQueryWrapper<>();
		 queryWrapper.last("limit 1");
		 //岩质边坡稳定性评价因子
		  rockSlopeStableSetting = this.rockSlopeStableSettingService.getOne(queryWrapper);
		 if(oConvertUtils.isNotEmpty(rockSlopeStableSetting)) {
			 //				//将数据缓存到redis中
             redisUtil.set(cacheKey, rockSlopeStableSetting);
             log.info("进行redis缓存成功");
             return Result.OK("进行redis缓存成功");
         }else {
             log.info("进行redis缓存失败");
             return Result.error("进行redis缓存失败");
		 }
	 }


	@AutoLog(value = "多表数据缓存-进行redis缓存")
	@ApiOperation(value="多表数据缓存-进行redis缓存", notes="多表数据缓存-进行redis缓存")
	@PostMapping("/redisCacheConfig")
	public Result<?> redisCacheConfig() {
		log.info("开始进行Redis缓存加载");

		// 用于记录是否有任意一个配置缺失
		boolean allCached = true;
		// 岩质边坡稳定性评价因子配置
		if (!tryLoadAndCache(CACHE_KEY_ROCK_SLOPE, rockSlopeStableSettingService)) {
			allCached = false;
		}
		// 边坡稳定性设置
		if (!tryLoadAndCache(CACHE_KEY_SLOPE, slopeStableSettingService)) {
			allCached = false;
		}
		// 土石边坡设置
		if (!tryLoadAndCache(CACHE_KEY_SOIL_ROCK_SLOPE, soilRockSlopeSettingService)) {
			allCached = false;
		}
		// 边坡风险评估设置
		if (!tryLoadAndCache(CACHE_KEY_SLOPE_RISK, slopeRiskEvaluationSettingService)) {
			allCached = false;
		}

		if (allCached) {
			return Result.OK("所有配置已成功缓存");
		} else {
			return Result.error("部分配置未找到，请检查数据库是否配置了对应的算法参数");
		}
	}
	/**
	 * 尝试从 Redis 获取缓存，若不存在则查询数据库并写入缓存
	 *
	 * @param cacheKey 缓存键名
	 * @param service 数据库服务
	 * @return 是否成功获取到数据（true=成功或已有缓存，false=数据库也没查到）
	 */
	private <T> boolean tryLoadAndCache(String cacheKey, IService<T> service) {
		// 1. 先尝试从 Redis 获取
		T cached = (T) redisUtil.get(cacheKey);
		if (oConvertUtils.isNotEmpty(cached)) {
			return true; // 已存在缓存
		}
		// 2. 缓存不存在，从数据库查询
		T fromDb = service.getOne(new QueryWrapper<>());
		if (oConvertUtils.isNotEmpty(fromDb)) {
			// 3. 写入 Redis，并设置过期时间（例如：24小时）
			redisUtil.set(cacheKey, fromDb);
			return true;
		}
		// 4. 数据库也没有
		log.warn("数据库中未找到对应配置，缓存 key: {}", cacheKey);
		return false;
	}

}
